package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/*
    Aspect注解:
    1.标识该类为切面类
    2.即为目标方法进行功能增强的类
 */
@Aspect
@Component
public class LogAspect {
    /**
     * 1.Before注解:前置通知 - 在目标方法调用之前执行
     */
    @Before("execution(public int cn.tedu._07springaop.aop.CalculatorIml.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        /*
            1.jionPoint:连接点参数
            2.获取方法名:joinPoint.getSignature().getName()
            3.获取目标方法参数:joinPoint.getArgs()
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[1-开始日志]:前置通知,"+name+"方法执行,参数为:"+args);
    }
    /**
     * 2.AfterReturning注解:返回通知 - 目标方法成功返回之后执行
     */
    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorIml.*(..))",
            returning = "r")
    public void afterReturningMethod(JoinPoint joinPoint,Object r){
        String name = joinPoint.getSignature().getName();
        System.out.println("2-返回通知:"+name+"方法结束,结果为:"+r);

    }
    /**
     * 3.异常通知
     */
    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorIml.*(..))",
            throwing="ex")
    public void afterThrowingMethod(JoinPoint joinPoint,Throwable ex){
        String name = joinPoint.getSignature().getName();
        System.out.println("3-异常通知:"+name+"方法异常,提示消息为:"+ex.getMessage());
    }

    /**
     *4.After注解:后置通知,当目标方法彻底结束[正常结束和异常结束]后执行
     */
    @After(value = "execution(public int cn.tedu._07springaop.aop.CalculatorIml.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        System.out.println("4-返回通知:目标方法彻底结束后执行");
    }

    /**
     * 5.Around注解:环绕通知,贯穿于所有阶段;
     *  等价于:@Before+@After+@AfterReturning+@AfterThrowing;
     */
    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorIml.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        Object result = null;
        try{
            //1.前置通知
            System.out.println("环绕1-前置通知");
            //2.执行目标方法
            result=joinPoint.proceed();
            //3.返回通知
            System.out.println("环绕2-返回通知");
        }catch (Throwable e){
            //4.异常通知
            System.out.println("环绕3-异常通知");
            throw new RuntimeException(e);
        }finally {
            //5.后置通知
            System.out.println("环绕4-后置通知");
        }
        return result;
    }
}
